import { getProvinceList, getCityList, getSchoolList, getGradeList, getClassList } from '@/api/data';

const formatch = (data, level, isChild = false) => {
	if (data.length > 0) {
		return data.map(function(value, index) {
			let province = {
				id: value.id,
				name: value.name
			};
			let info = {
				label: value.name,
				value: JSON.stringify(province),
				level: level
			};

			if (isChild) {
				info['children'] = [];
				info['loading'] = false;
			}

			return info;
		});
	} else {
		return [
			{
				label: '暂无数据',
				disabled: true,
				value: ''
			}
		];
	}
};

export const getAreasList = (item, callback, level) => {
	if (item.level == 0) {
		let params = {
			isPage: 0
		};
		getProvinceList(params).then(res => {
			if (item.level == level) {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, false);
			} else {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, true);
			}
			callback(item);
		});
	} else if (item.level == 1) {
		let params = {
			isPage: 0,
			provinceid: JSON.parse(item.value).id
		};
		getCityList(params).then(res => {
			if (item.level == level) {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, false);
			} else {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, true);
			}
			callback(item);
		});
	} else if (item.level == 2) {
		let params = {
			isPage: 0,
			cityid: JSON.parse(item.value).id
		};
		getSchoolList(params).then(res => {
			if (item.level == level) {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, false);
			} else {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, true);
			}
			callback(item);
		});
	} else if (item.level == 3) {
		let params = {
			isPage: 0,
			schoolid: JSON.parse(item.value).id
		};

		getGradeList(params).then(res => {
			if (item.level == level) {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, false);
			} else {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, true);
			}
			callback(item);
		});
	} else if (item.level == 4) {
		let params = {
			isPage: 0,
			gradeid: JSON.parse(item.value).id
		};
		getClassList(params).then(res => {
			if (item.level == level) {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, false);
			} else {
				item['children'] = formatch(res.data.data, parseInt(item.level) + 1, true);
			}
			callback(item);
		});
	}
};
